<?php

class SJB_Classifieds_PayForListing extends SJB_Function
{
	public function execute()
	{
		$listing_id = isset($_REQUEST['listing_id']) ? $_REQUEST['listing_id'] : null;
		$listing = SJB_ListingManager::getObjectBySID($listing_id);

		if (!is_null($listing)) {
			$listingInfo = SJB_ListingManager::getListingInfoBySID($listing_id);
			if (isset($listingInfo['complete']) && $listingInfo['complete'] == 1) {
				$listingInfo = SJB_ListingManager::getListingInfoBySID($listing_id);
				$productInfo = !empty($listingInfo['product_info']) ? unserialize($listingInfo['product_info']) : array();
				$price = 0;
				// // проверить истек ли листинг, если истек , прайс прировнять к renewal_price
				if (SJB_ListingManager::getIfListingHasExpiredBySID($listing->getID()) && isset($productInfo['renewal_price']))
					$price = $productInfo['renewal_price'];

				if ($price != 0) {
					$user_sid = $listing->getUserSID();
					$items['products'][1]  = '-1';
					$subTotalPrice = $price;
					$items['price'][1] = sprintf('%.02f', $subTotalPrice);
					$items['amount'][1] = sprintf('%.02f', $subTotalPrice);
					$items['custom_item'][1] = 'Payment for listing(s) #: ' . $listing_id;
					$items['custom_info'][1] =  array('listings_ids' => $listing_id, 'type' => 'activateListing');
					$items['qty'][1] = '1';
					$tax_info = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($user_sid, $subTotalPrice);
					$totalPrice = SJB_InvoiceManager::getTotalPrice($subTotalPrice, $tax_info['tax_amount'], $tax_info['price_includes_tax']);
					$invoice_info = array(
						'user_sid' => $user_sid,
						'include_tax' => !empty($tax_info['tax_info']['tax_name']) ? 1 : 0,
						'total' => $totalPrice,
						'sub_total' => $subTotalPrice,
						'success_page_url' => SJB_System::getSystemSettings('SITE_URL') . "/activate-listing/",
						'status' => SJB_Invoice::INVOICE_STATUS_UNPAID,
						'tax_info' => $tax_info,
						'items' => $items,
						'is_recurring' => false
					);
					$invoice_sid = SJB_InvoiceManager::generateInvoice($invoice_info);
					$payment_page_url = SJB_System::getSystemSettings('SITE_URL') . "/payment-page/?invoice_sid=" . $invoice_sid;
					SJB_HelperFunctions::redirect($payment_page_url);
					return;
				}
				else
					SJB_ListingManager::activateListingBySID($listing->getSID());
			}
			else
				$errors['LISTING_IS_NOT_COMPLETE'] = 1;
		}
		elseif (is_null($listing_id)) {
			$errors['LISTING_ID_NOT_SPECIFIED'] = 1;
		}
		else {
			$errors['WRONG_LISTING_ID'] = 1;
		}

		$template_processor = SJB_System::getTemplateProcessor();
		$template_processor->assign("errors", isset($errors) ? $errors : null);
		$template_processor->display("pay_for_listing.tpl");
	}
}
